import { createRoot } from 'react-dom/client'
import React from 'react'
import {
  HashRouter,
  BrowserRouter,
  Routes,
  Route,
  Link,
  NavLink,
  Navigate,
  useRoutes,
} from './react-router-dom'

// import Home from './components/Home.jsx'
// import User from './components/User.jsx'
// import UserAdd from './components/UserAdd.jsx'
// import UserList from './components/UserList.jsx'
// import UserDetail from './components/UserDetail.jsx'
// import Profile from './components/Profile.jsx'
// import Post from './components/Post.jsx'
// import NotFound from './components/NotFound.jsx'
// import Login from './components/Login'
// import Protected from './components/Protected'

import routesConfig from './routesConfig'
const LazyPost = React.lazy(() => import('./components/Post')) // 懒加载

// 激活的样式对象
const activeStyle = {
  backgroundColor: 'green',
}
// 激活的类名
const activeClassName = 'active'
// 激活的导航属性对象
const activeNavProps = {
  style: ({ isActive }) => isActive ? activeStyle : ({}),
  className: ({ isActive }) => isActive ? activeClassName : ''
}

const root = createRoot(document.getElementById('root'))

function App() {
  const [routes, setRoutes] = React.useState(routesConfig)
  const addRoute = () => {
    setRoutes((prevRoutes) => {
      return [
        ...prevRoutes,
        {
          path: '/post/:id',
          // 懒加载 当LazyPost组件没有加载成功前会显示 fallback 中的组件
          element: <React.Suspense fallback={<div>loading...</div>}>
            <LazyPost />
          </React.Suspense>,
        }
      ]
    })
  }
  return <div>
    {useRoutes(routes)}
    <button onClick={addRoute}>增加post路由组件</button>
  </div>
}

root.render(
  // 路由容器
  <HashRouter>
    <ul>
      <li><NavLink to="/" {...activeNavProps} end={true}>首页</NavLink></li>
      <li><NavLink to="/user" {...activeNavProps}> 用户管理</NavLink></li>
      <li><NavLink to="/profile" {...activeNavProps}>profile</NavLink></li>
      <li><NavLink to="/login" {...activeNavProps}>login</NavLink></li>
      <li><NavLink to="/post/123" {...activeNavProps}>文章</NavLink></li>
    </ul>
    {/* 里面保存路由规则  */}
    {/* <Routes> */}
    {/* 每个 Route 组件代表一个路由规则 */}
    {/* <Route path='/' element={<Home />}></Route> */}

    {/* <Route path='/user' element={<User></User>}>
        <Route path="add" element={<UserAdd></UserAdd>}></Route>
        <Route path="list" element={<UserList></UserList>}></Route>
        <Route path="detail/:id" element={<UserDetail></UserDetail>}></Route>
      </Route> */}
    {/* 受保护路由 只有登录了才允许访问 Profile 组件 */}
    {/* <Route path='/profile' element={<Protected component={Profile} path="/profile" />}></Route>
      <Route path='/login' element={<Login />}></Route>
      <Route path='/post/:id' element={<Post />}></Route> */}
    {/* <Route path="*" element={<NotFound />}></Route> */}
    {/* <Route path="*" element={<Navigate to="/" />}></Route> */}
    {/* </Routes> */}
    <App></App>
  </HashRouter>
)
